package com.common.base.app.activity

import android.R
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Selection
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ScrollView
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.common.base.app.extras.*
import com.common.base.app.recycler.header.LoadingHeader
import com.common.base.utils.*
import com.common.base.widget.PlaceholderView
import com.jeremyliao.liveeventbus.LiveEventBus
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshFooter
import com.scwang.smart.refresh.layout.api.RefreshHeader
import com.umeng.analytics.MobclickAgent
//import com.umeng.socialize.UMShareAPI
import me.yokeyword.fragmentation.SupportActivity


/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/8/19
 * <p>
 * 描述：activity 基类
 * <p>
 * 修订历史：
 */
abstract class BaseActivity : SupportActivity() {

    private var handleHideSoftInput = true

    var isActivityVisible = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        ActivityCollector.instance?.addActivity(this)
        initPre()
        setContentView(getLayoutResView())
        initViews()
        initViews(savedInstanceState)
        initEvents()
    }

    override fun attachBaseContext(newBase: Context?) {
//        super.attachBaseContext(newBase)
//        Log.e(TAG, "attachBaseContext");
        super.attachBaseContext(newBase?.let { MultiLanguageUtil.attachBaseContext(it) })
        //app杀进程启动后会调用Activity attachBaseContext
        MultiLanguageUtil.instance?.setConfiguration(newBase)
    }

    open fun initPre() {
        StatusBarUtils.setStatusBarForegroundColor(this, isStatusBarForegroundBlack())
        // 沉浸式
        if (isStatusBarTranslate()) {
            StatusBarUtils.setStatusBarTranslucent(this)
        } else {
            StatusBarUtils.setStatusBarColor(this, Color.WHITE)
        }
        LiveEventBus.get("key_logout_app").observe(this) {
            finish()
        }
    }

    override fun onResume() {
        super.onResume()
        isActivityVisible = true
        MobclickAgent.onPageStart(this.javaClass.name)//友盟页面跟踪
        MobclickAgent.onResume(this)
        AppUtils.isNeedUpdateApp(this).yes { LiveEventBus.get("appUpdate").post(true) }
    }

    override fun onPause() {
        super.onPause()
        isActivityVisible = false
        MobclickAgent.onPageEnd(this.javaClass.name)//友盟页面跟踪
        MobclickAgent.onPause(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        // 如果该活动被销毁了，就将此活动从ActivityCollector类里的list中移除
        ActivityCollector.instance?.removeActivity(this)
    }

    open fun showLoading() {
        if (isShowLoading()) {
            showPageLoading(getPlaceholderView())
        }
    }

    open fun showContent() {
        showPageContent(getPlaceholderView())
    }

    open fun showError(msg: String? = null) {
        if (isShowError()) {
            showPageError(getPlaceholderView(), msg)
        }
    }

    protected open fun showEmpty(msg: String? = null) {
        showPageEmpty(getPlaceholderView(), msg)
    }

    protected open fun setErrorRetryListener(listener: () -> Unit) {
        setPageErrorRetryListener(getPlaceholderView(), listener)
    }


    abstract fun getLayoutResView(): View

    /**
     * 子类初始化View
     */
    protected open fun initViews() {

    }

    /**
     * 子类初始化View
     */
    protected open fun initViews(savedInstanceState: Bundle?) {

    }

    /**
     * 初始化控件的事件
     */
    protected open fun initEvents() {
        setErrorRetryListener { showEmpty() }
        initRefreshLayout()
    }

    /**
     * 设置状态栏文本颜色为黑色
     */
    open fun isStatusBarForegroundBlack(): Boolean = true

    /**
     * 状态栏是否沉浸
     */
    protected open fun isStatusBarTranslate(): Boolean = false

    /**
     * 占位控件
     */
    open fun getPlaceholderView(): PlaceholderView? = null

    open fun isShowLoading(): Boolean = true

    open fun isShowError(): Boolean = true


    /**
     * 子类提供一个刷新控件的引用
     */
    open fun getSmartRefreshLayout(): SmartRefreshLayout? = null

    /**
     * finishLoadMore是否延迟
     */
    open fun isDelayFinishLoadMore(): Boolean = true


    /**
     * 初始化刷新控件
     */
    private fun initRefreshLayout() {
        (getSmartRefreshLayout() == null).yes { return }
        setSmartLayoutAttrs()
        getRefreshHeader()?.let { getSmartRefreshLayout()?.setRefreshHeader(it) }
        getRefreshFooter()?.let { getSmartRefreshLayout()?.setRefreshFooter(it) }
        getSmartRefreshLayout()?.setOnRefreshListener {
            onRefreshListener()
        }
        getSmartRefreshLayout()?.setOnLoadMoreListener {
            onLoadMoreListener()
        }
    }

    /**
     * 设置SmartRefreshLayout相关属性
     */
    protected fun setSmartLayoutAttrs() {
        getSmartRefreshLayout()?.setEnableAutoLoadMore(isEnableAutoLoadMore())
        getSmartRefreshLayout()?.setEnableLoadMore(isEnableLoadMore())
        getSmartRefreshLayout()?.setEnableRefresh(isEnableRefresh())
        getSmartRefreshLayout()?.setEnableOverScrollBounce(isEnableOverScrollBounce())
        getSmartRefreshLayout()?.setEnablePureScrollMode(isEnablePureScrollMode())
        getSmartRefreshLayout()?.setEnableOverScrollDrag(isEnableOverScrollDrag())
        getSmartRefreshLayout()?.setEnableLoadMoreWhenContentNotFull(false)
    }

    //下拉刷新
    protected open fun onRefreshListener() {
        hideRefreshing(false)
    }

    //加载更多
    protected open fun onLoadMoreListener() {
        hideRefreshing(false)
    }


    /**
     * 获取下拉刷新的头部
     */
    protected open fun getRefreshHeader(): RefreshHeader? {
        return LoadingHeader(this)
    }

    /**
     * 获取刷新底部
     */
    protected open fun getRefreshFooter(): RefreshFooter? {
        return ClassicsFooter(this)
    }

    /**
     * 结束刷新
     */
    open fun hideRefreshing(hasMore: Boolean = true) {
        if (isDelayFinishLoadMore()) {
            getSmartRefreshLayout()?.finishRefresh()
        } else {
            getSmartRefreshLayout()?.finishRefresh(0)
        }
        if (hasMore) {
            if (isDelayFinishLoadMore()) {
                getSmartRefreshLayout()?.finishLoadMore()
            } else {
                getSmartRefreshLayout()?.finishLoadMore(0)
            }
        } else {
            getSmartRefreshLayout()?.finishLoadMoreWithNoMoreData()
        }
    }

    open fun autoRefresh() {
        getNestedScrollView()?.fullScroll(ScrollView.FOCUS_UP)
        getRecyclerView()?.smoothScrollToPosition(0)
        getSmartRefreshLayout()?.autoRefresh()
    }

    open fun getNestedScrollView(): NestedScrollView? {
        return null
    }

    open fun getRecyclerView(): RecyclerView? {
        return null
    }


    /**
     * 竖直滚动条是否可用
     */
    protected open fun isVerticalScrollBarEnabled() = false

    /**
     * 水平滚动条是否可用
     */
    protected open fun isHorizontalScrollBarEnabled() = false

    /**
     * 是否可以自动加载更多，默认可以
     */
    protected open fun isEnableAutoLoadMore() = true

    /**
     * 是否可以加载更多，默认可以
     */
    protected open fun isEnableLoadMore() = true

    /**
     * 是否可以刷新，默认可以
     */
    protected open fun isEnableRefresh() = true

    /**
     * 是否是纯净模式，不展示刷新头和底部，默认false
     */
    protected open fun isEnablePureScrollMode() = false

    /**
     * 刷新时是否可以越界回弹
     */
    protected open fun isEnableOverScrollBounce() = false

    /**
     * 设置是否在没有更多数据之后 Footer 跟随内容
     */
    protected open fun isEnableFooterFollowWhenNoMoreData() = false

    /**
     * 是否可拖拽
     */
    protected open fun isEnableOverScrollDrag() = false

    /**
     * 默认展示加载页面
     */
    protected open fun isShowLoadingPage() = true

    /**
     * 是否展示加载对话框
     */
    protected open fun isShowLoadingDialog() = false

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {

        val parent = this.findViewById<View>(R.id.content) as ViewGroup

        //获取当前触摸到的View
        val touchedView = getTouchTarget(
            parent, ev.x.toInt(),
            ev.y.toInt()
        )

        if (touchedView != null && touchedView is EditText) {
            return super.dispatchTouchEvent(ev)
        }

        if (ev.action == MotionEvent.ACTION_DOWN && handleHideSoftInput) {
            // 是否需要隐藏软键盘
            val flag = SoftInputUtils.isHideSoftInput(ev)
            if (flag) {
                SoftInputUtils.invokeOnTouchOutsideListener(this)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    fun unEnableHandleHideSoftInput() {
        handleHideSoftInput = false
    }

    fun enableHandleHideSoftInput() {
        handleHideSoftInput = true
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
//        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)//友盟分享回调
    }

    /**
     * 设置根布局参数
     */
    private fun setRootView() {
        val parent = this.findViewById<View>(R.id.content) as ViewGroup
        var i = 0
        val count = parent.childCount
        while (i < count) {
            val childView = parent.getChildAt(i)
            if (childView is ViewGroup) {
                childView.setFitsSystemWindows(true)
                childView.clipToPadding = true
            }
            i++
        }
    }

    /**
     * 设置光标
     */
    open fun setCursor(mEditText: EditText?) {
        if (mEditText != null) {
            val editable = mEditText.text
            //新字符串的长度
            val newLen = mEditText.length()
            //设置新光标所在的位置
            Selection.setSelection(editable, newLen)
        }
    }

    //根据坐标返回触摸到的View
    private fun getTouchTarget(rootView: View, x: Int, y: Int): View? {
        var targetView: View? = null
        // 判断view是否可以聚焦
        val touchableViews = rootView.touchables
        for (touchableView in touchableViews) {
            if (isTouchPointInView(touchableView, x, y)) {
                targetView = touchableView
                break
            }
        }
        return targetView
    }

    //(x,y)是否在view的区域内
    private fun isTouchPointInView(view: View?, x: Int, y: Int): Boolean {
        if (view == null) {
            return false
        }
        val position = IntArray(2)
        view.getLocationOnScreen(position)
        val left = position[0]
        val top = position[1]
        val right = left + view.measuredWidth
        val bottom = top + view.measuredHeight
        return x in left..right && y >= top && y <= bottom
    }
}